package cn.lrbj.grpc.server.provider;

import java.io.File;
import java.io.IOException;

import javax.print.PrintService;

import java.awt.print.PrinterJob;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.Orientation;
import org.apache.pdfbox.printing.PDFPageable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.grpc.service.pdfprint.PrinterProvider.Message.Builder;
import cn.grpc.service.pdfprint.DdfPrintProviderGrpc.DdfPrintProviderImplBase;
import cn.grpc.service.pdfprint.PrinterProvider.Message;
import cn.grpc.service.pdfprint.PrinterProvider.RequestParam;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

@GrpcService
public class PdfPrintProvider extends DdfPrintProviderImplBase {

    // 定义日志输出
    private final Logger logger = LoggerFactory.getLogger(UserProvider.class);

    @Override
    public void goPtPdf(RequestParam request, StreamObserver<Message> responseObserver) {
        logger.info("request ===> " + request.getDpfPath() + "------" + request.getPrinterName());
        Builder msg = runPdfServer(request.getPrinterName(), request.getDpfPath());

        responseObserver.onNext(msg.build());
        responseObserver.onCompleted();
    }

    /**
     * @param printerName 打印机名包含字串 192.168.10.8
     * @param dpfPath     pdf 文件路径
     * @return 消息json
     */
    private Builder runPdfServer(String printerName, String dpfPath) {
        PDDocument document = null;
        Builder msg = Message.newBuilder();
        try {
            document = PDDocument.load(new File(dpfPath));
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setJobName(new File(dpfPath).getName());

            PrintService[] printService = PrinterJob.lookupPrintServices(); // 获得本台电脑连接的所有打印机

            boolean flag = true;
            for (PrintService service : printService) {
                if (service.getName().contains(printerName)) {
                    printJob.setPrintService(service);
                    flag = false;
                    break;
                }
            }
            if (flag) {
                msg.setCode(-1);
                msg.setMsg("找不到该打印机");
                return msg;
            }

            printJob.setPageable(new PDFPageable(document, Orientation.AUTO, false, 0));
            printJob.print();

            msg.setCode(0);
            msg.setMsg("success");
        } catch (Exception e) {
            msg.setCode(-1);
            msg.setMsg("未知错误 ===> " + e.getMessage());
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return msg;
    }
}
